<?php
/**
 * 红包开启
 * Class RedOpen
 */
namespace App;
defined('IN_IA') or exit('Access Denied');

use Model\CashMod;
use Model\MemberMod;
use Model\RedBatchMod;
use Model\RedMod;
use Model\RedRecordMod;
use Pri\red\RedLuckPrivate;
use Pub\cache\Cache;
use Pub\tool\Setting as SettingCache;
use Pub\tool\Tool;
use Pub\wx\WxPay;

class RedOpen extends Action
{
    private $Red = null;
    private $RedRecord = null;  //红包记录
    private $RedBatch = null;  //红包批数
    private $RedLuck = null;  //手气红包公用方法
    private $Member = null;  //会员
    private $Cash = null;  //提现

    private $_red_id = 0;  //红包id
    private $_red = array();  //红包详情
    private $_red_money = 0;  //开的红包金额

    private $_batch = array();  //红包批量数
    private $_red_record = array();  //红包记录

    public function __construct()
    {
        parent::__construct();
        $this->Red = new RedMod();
        $this->getUid();
        if($this->_gpc['red_id']) $this->_red_id = $this->_gpc['red_id'];
        $this->_red = $this->Red->findOne(array('id'=>$this->_red_id),array('status','money','number','already_number',"type"));
    }

    /**
     * 开红包
     */
    public function index()
    {
        //验证当前红包状态
        $this->checkStatus();
        //验证当前用户是不是开启过当前红包
        $this->userAlreadyOpenRed();
        //验证当前红包可开启数量
        $this->redAlreadyNumber();
        //开的红包金额
        $this->redMoney();
        //是否自动到账用户微信钱包
        if(!$this->autoToWxWallet()){
            //开启用户添加余额
            $this->addMemberBalance();
        }
        //添加记录
        $this->addRecord();
        //添加红包已开数量
        $this->addAlreadyNumber();
        $this->_result = array('status'=>'success','data'=>array('money'=>$this->_red_money));
        $this->result($this->_result);
    }

    /**
     * 验证红包当前状态
     */
    private function checkStatus()
    {
        if($this->_red['status'] != 2){
            if($this->_red['status'] == 3){
                $this->_result = array('status'=>'error','err_status'=>1,'err_msg'=>'您来晚了，红包已被抢完');
            }else if($this->_red['status'] == 4){
                $this->_result = array('status'=>'error','err_status'=>2,'err_msg'=>'当前红包已关闭');
            }else if($this->_red['status'] == 9){
                $this->_result = array('status'=>'error','err_status'=>3,'err_msg'=>'当前红包已经被删除');
            }else{
                $this->_result = array('status'=>'error','err_status'=>-1,'err_msg'=>'未知错误');
            }
            $this->result($this->_result);
        }
    }

    /**
     * 用户是否已经开启红包
     */
    private function userAlreadyOpenRed()
    {
        $this->RedRecord = new RedRecordMod();
        if($this->RedRecord->findOne(array('uid'=>$this->_uid,'red_id'=>$this->_red_id),array('id'))){
            $this->_result = array('status'=>'error','err_status'=>5,'err_msg'=>'您已开过此红包了');
            $this->result($this->_result);
        }
    }

    /**
     * 红包开启数量验证
     */
    private function redAlreadyNumber()
    {
        if($this->_red['already_number'] >= $this->_red['number']){
            $this->Red->update(array('status'=>3),array('id'=>$this->_red_id));
            $this->_result = array('status'=>'error','err_status'=>6,'err_msg'=>'您来晚了，红包已被抢完');
            $this->result($this->_result);
        }
    }

    /**
     * 开启红包余额
     */
    private function redMoney()
    {
        if($this->_red["type"] == 2){
            //普通红包
            $this->_red_money = $this->_red['money'];
        }else{
            //拼手气红包
            //1、检测红包是不是已分批
            if($this->testBatch()){
                //分批
                //1、请求分批数据
                $this->getBatch();
                //2、判断是否继续生成分批红包
                $_is_create = $this->testCreateBatch();
                //3、可生成分批红包
                if($_is_create !== 0){
                    $this->RedLuck = new RedLuckPrivate();
                    $_number = KUYUAN_LUCK_RED_DIVISOR;
                    $_money = $this->_batch["money"];
                    if($_is_create === 2){
                        if($this->_batch["last_count"] != 0) $_number = $this->_batch["last_count"];
                        $_money = $this->_batch["last_money"];
                    }
                    //生成随机红包数据
                    $_red_data = $this->RedLuck->redPicket($_money,$_number);
                    $_record = array(
                        "uniacid"=>$this->_uniacid,
                        "uid"=>0,
                        "red_id"=>$this->_gpc["red_id"]
                    );
                    //写入数据
                    foreach($_red_data as $_v){
                        $_record["money"] = $_v;
                        $this->RedRecord->insert($_record);
                    }
                    //新增红包批数
                    $this->RedBatch->math(array("already_create_count +"=>1),array("red_id"=>$this->_red_id));
                }
            }
            //2、获取一个红包记录，设置红包金额
            $this->_red_record = $this->RedRecord->findOne(array("red_id"=>$this->_red_id,"uid"=>0),array("id","money"));
            $this->_red_money = $this->_red_record["money"];
        }
    }

    /**
     * 自动到账用户钱包
     */
    private function autoToWxWallet()
    {
        $_result = false;
        //用户最低可提现金额
        $_lowest_cash = SettingCache::get(SettingCache::LOWEST_CASH);
        //自动到账金额限制
        $_auto_cash = SettingCache::get(SettingCache::AUTO_CASH);
        //是否自动到账
        if($this->_red_money >= $_lowest_cash && $_auto_cash > 0 && $this->_red_money < $_auto_cash){
            $_cash_order_id = Tool::createOrder();
            $WxPay = new WxPay($_cash_order_id);
            $_fans = $this->uidToFans($this->_uid);
            $_openid = KUYUAN_DEBUG ? 'oxYQT1DAyMPEFXMzjjJ-Rz1OQa-c' : $_fans['openid'];
            $_remark = SettingCache::get(SettingCache::CASH_REMARK);
            $_wx_payer = $WxPay->payer($_openid,$this->_red_money,$_remark ? $_remark : "提现到账");
            if($_wx_payer['status'] == 'success'){
                $this->Cash = new CashMod();
                $this->Cash->insert(array(
                    'uniacid'=>$this->_uniacid,
                    'order_id'=>$_cash_order_id,
                    'uid'=>$this->_uid,
                    'money'=>$this->_red_money,
                    'time'=>TIMESTAMP,
                    'status'=>1
                ));
                $_result = true;
            }
        }
        return $_result;
    }

    /**
     * 红包添加余额
     */
    private function addMemberBalance()
    {
        $_use_balance = SettingCache::get(SettingCache::USE_BALANCE);
        if($_use_balance == 1){
            $this->Member = new MemberMod();
            $this->Member->math(array('balance +'=>$this->_red_money),array('uid'=>$this->_uid,'uniacid'=>$this->_uniacid));
        }else{
            mc_credit_update($this->_uid,"credit2",$this->_red_money,
                array(
                    0,
                    SettingCache::get(SettingCache::WEB_NAME)."开红包",
                    "kuyuan_red",
                    0,
                    0,
                    1
                    )
            );
        }
    }

    /**
     * 添加红包记录
     */
    private function addRecord()
    {
        if($this->_red["type"] == 1){
            //手气红包，更改记录uid，生成开包时间
            $this->RedRecord->update(array(
                "uid"=>$this->_uid,
                "time"=>TIMESTAMP
            ),array("id"=>$this->_red_record["id"]));
        }else{
            //普通红包新增记录
            $this->RedRecord->insert(array(
                'uniacid'=>$this->_uniacid,
                'uid'=>$this->_uid,
                'red_id'=>$this->_red_id,
                'money'=>$this->_red_money,
                'time'=>TIMESTAMP
            ));
        }
    }

    /**
     * 添加红包已开数量
     */
    private function addAlreadyNumber()
    {
        $this->Red->math(array('already_number +'=>1),array('id'=>$this->_red_id));
    }

    //-----------拼手气相关----------------

    /**
     * 红包是否分批
     */
    private function testBatch()
    {
        if($this->_red["number"] >= KUYUAN_LUCK_RED_DIVISOR*2){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 获得分批数据
     */
    private function getBatch()
    {
        $this->_batch = Cache::get(Cache::RED_BATCH,array("red_id"=>$this->_gpc["red_id"]));
        if(!$this->_batch || KUYUAN_DEBUG){
            if(!$this->RedBatch instanceof RedBatchMod) $this->RedBatch = new RedBatchMod();
            $this->_batch = $this->RedBatch->findOne(array("red_id"=>$this->_red_id),array("create_count","last_count","money","last_money"));
            Cache::set(Cache::RED_BATCH,$this->_batch,array("red_id"=>$this->_gpc["red_id"]));
        }
    }

    /**
     * 检测是否生成剩余红包
     * @return integer 0=无剩余批数 1=有 2=最后一批
     */
    private function testCreateBatch()
    {
        $_batch_complete = Cache::get(Cache::RED_BATCH_COMPLETE,array("red_id"=>$this->_red_id));
        if(!$_batch_complete || KUYUAN_DEBUG){
            if(!$this->RedBatch instanceof RedBatchMod) $this->RedBatch = new RedBatchMod();
            $_batch = $this->RedBatch->findOne(array("red_id"=>$this->_red_id),array("already_create_count"));
            $_diff = $this->_batch["create_count"] - $_batch["already_create_count"];
            if($_diff <= 0){
                Cache::set(Cache::RED_BATCH_COMPLETE,"1",array("red_id"=>$this->_gpc["red_id"]));
                return 0;  //无剩余批数
            }else if($_diff == 1){
                return 2;  //最后一批
            }else if($_diff > 1){
                return 1;
            }
        }else{
            return 0;
        }
    }
}
